#include<iostream>

using namespace std;

struct ListNode {
    int val;
    ListNode* next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode* next) : val(x), next(next) {}
};

ListNode* reverseKGroup(ListNode* head, int k) {
    auto guard = new ListNode(-1);
    guard->next = head;
    auto prev = guard, cur = head;
    while (cur)
    {
        for (int i = 0; i < k - 1; i++)
        {
            cur = cur->next;
            if (!cur)
                return guard->next;
        }
        auto next = cur->next, nprev = prev->next;
        reverse(prev, cur);
        prev = nprev;
        cur = next;
    }
    return guard->next;
}

void reverse(ListNode* head, ListNode* end)
{
    auto cur = head->next, tail = end->next, ntail = cur;
    end->next = nullptr, head->next = nullptr;
    while (cur)
    {
        auto next = cur->next;
        cur->next = head->next;
        head->next = cur;
        cur = next;
    }
    ntail->next = tail;
}